<?php

namespace App\Admin\Forms;

use App\Models\TongUser;
use App\Models\TongUserOpera;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class UpdatePid extends Form
{
    use LazyWidget;
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
         //dd($input);
        if($input['p_id']==$input['id']){
            return $this
                ->response()
                ->warning('修改邀请人失败')
                ->refresh();
        }
        $p_user_query = TongUser::query()->where('id',$input['p_id']);
        if(!$p_user_query->exists()){
            return $this
                ->response()
                ->warning('邀请人id输入有误')
                ->refresh();
        }
        // return $this->response()->error('Your error message.');
        DB::transaction(function () use($input) {
            $user_info = TongUser::query()->where('id',$input['id'])->first();
            $pre = $user_info['p_id'];
            if($pre!=0){
                $p_info = TongUser::query()->where('id',$pre)->first();
            }else{
                $p_info['nickname'] = '顶级用户';
            }


            $n_info = TongUser::query()->where('id',$input['p_id'])->first();
            TongUser::query()->where('id',$input['id'])->update(['p_id'=>$input['p_id'],'child_month_order'=>0]);
            updateUserPid($input['id'],$input['p_id']);

            //增加操作记录
            $admin_id = Admin::user()->id;
            TongUserOpera::query()->create([
                'admin_id'=>$admin_id,
                'type'=>5,
                'u_id'=>$input['id'],
                'desc'=>json_encode(['pre'=>'用户邀请人修改前：'.$p_info['nickname'],'next'=>'用户邀请人修改后：'.$n_info['nickname']])
            ]);
        });
        return $this
            ->response()
            ->success('修改邀请人')
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->hidden('id', 'id')->required();
        $this->text('p_id','邀请人')->required()->help('这里需要填入的是邀请人的id,修改邀请关系后用户的业绩将会从0开始计算,原有的业绩不会带过来');
        //$user_list = TongUser::query()->where('id','!=',$this->payload['id'])->pluck('mobile','id');
        //$this->select('p_id', '邀请人')->options($user_list)->required();
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
            'id' => $this->payload['id'] ?? null,
            'p_id' => $this->payload['p_id'] ?? 0,
        ];
    }
}
